<!-- 我的 -->
<template>
    <div class="box">
        <div class="top_banner">
            <div class="pic"></div>
            <div class="login" @click="handleLogin" :class="{ 'logged-in': userInfo.isLogin }">
                {{ userInfo.isLogin ? userInfo.qqNumber : '登录' }}
            </div>
            <div class="tipText">
                {{ userInfo.isLogin ? '已登录，数据已同步到云端' : '登录后可将数据同步到云端' }}
            </div>
        </div>
        <div class="content">
            <div class="itemMax">
                <div class="item">
                    <div class="left">
                        <svgIcon iconName="icon-VIP" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        升级VIP
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax">
                <div class="item" style="border-bottom: 1px solid gray" v-for="(item,index) in myObj" @click="item.click">
                    <div class="left">
                        <svgIcon :iconName="item.icon" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        {{item.text}}
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax">
                <div class="item" style="border-bottom: 1px solid gray;">
                    <div class="left">
                        <svgIcon iconName="icon-shuchuguanli" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        导出账单
                    </div>
                    <div class="right" @click="handleFeatureClick">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
                <div class="item">
                    <div class="left">
                        <svgIcon iconName="icon-wenjianchuanshu" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        保存数据到云端(防丢失)
                    </div>
                    <div class="right" @click="handleFeatureClick">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax">
                <div class="item" style="border-bottom: 1px solid gray" v-for="(item,index) in myObj2" @click="item.click">
                    <div class="left">
                        <svgIcon :iconName="item.icon" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        {{item.text}}
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax">
                <div class="item" @click="handleFeatureClick">
                    <div class="left">
                        <svgIcon iconName="icon-bianji" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        关于女生记账
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax">
                <div class="item" @click="handleLogout" v-if="userInfo.isLogin">
                    <div class="left">
                        <svgIcon iconName="icon-CRM_icon_tuichu" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        退出登录
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
            <div class="itemMax" style="height: 230px;">
                <div class="item" @click="handleFeatureClick">
                    <div class="left">
                        <svgIcon iconName="icon-zhuxiao" font-size="40px"></SvgIcon>
                    </div>
                    <div class="center">
                        账号注销
                    </div>
                    <div class="right">
                        <svgIcon iconName="icon-youjiantou" font-size="30px" color="#000"></SvgIcon>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="lg_black" v-if="lg_flag" @click="handleBlackClick"></div>
    <div class="lg_cont" v-if="lg_flag">
        <div class="lg_top">
            <div class="lg_back" @click="handleBack">
                X
            </div>
            <div class="lg_title">登录账号更多惊喜等你发现</div>
        </div>
        <div class="lg_bannerr"></div>
        
        <!-- 邮箱登录表单 -->
        <div class="email-login">
            <div class="input-group">
                <input 
                    type="text" 
                    v-model="email" 
                    placeholder="请输入QQ邮箱" 
                    maxlength="30"
                    @input="validateEmail"
                >
            </div>
            <div class="input-group verify-code">
                <input type="text" v-model="verifyCode" placeholder="请输入验证码" maxlength="6">
                <button 
                    @click="sendVerifyCode" 
                    :disabled="!isEmailValid || countdown > 0"
                    class="send-code-btn"
                    :class="{ 'btn-active': isEmailValid && countdown === 0 }"
                >
                    {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
                </button>
            </div>
            <button class="login-btn" @click="handleEmailLogin">登录</button>
        </div>

        <div class="lg_xy">
            <input type="radio" id="lg_xy" />
            <label for="lg_xy">同意女生记账《隐私政策》和《用户服务协议》</label>
        </div>
    </div>
    <tab-bar />
    <MessageBox ref="messageBox" />
</template>

<script>
import TabBar from '@/components/TabBar.vue'
import MessageBox from '@/components/MessageBox.vue'
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import request from '../utils/request';
import { useStore } from 'vuex';
import pic from '../assets/my/pic.png';
import defaultPic from '../assets/my/pic_mr.png';

export default {
    components: {
        TabBar,
        MessageBox
    },
  setup() {
        const router = useRouter();
        const route = useRoute();
        const store = useStore();
        const userInfo = ref({
            nickname: '',
            headimgurl: '',
            isLogin: false,
            email: ''
        });

    const myObj = reactive([
        {
            icon: 'icon-diwuleibie',
            text: '类别设置',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                } else {
                    router.push('/type');
                }
            }
        },
        {
            icon: 'icon-wodexunzhang',
            text: '我的勋章',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-naozhong',
            text: '记账提醒',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-suo',
            text: '密码设置',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                } else {
                    router.push('/password');
                }
            }
        },
        {
            icon: 'icon-pifu',
            text: '皮肤装扮',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                } else {
                    router.push('/skinStryle');
                }
            }
        },
        {
            icon: 'icon-zitiyangshi',
            text: '字体颜色',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-shanchu1',
            text: '最近删除',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-a-shezhi-shucaidanshezhi',
            text: '更多设置',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        }
    ])
    const myObj2 = reactive([
        {
            icon: 'icon-10changyongwentijieda',
            text: '常见问题汇总',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-yijian',
            text: '有意见去反馈',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-kefu',
            text: '客服(工作日9:00 - 18:00)',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-haopingA',
            text: '为女生记账写好评',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        },
        {
            icon: 'icon-shoucangwenjian',
            text: '将女生记账推荐给好友',
            click: () => {
                if (!userInfo.value.isLogin) {
                    lg_flag.value = true;
                }
            }
        }
    ])

        const lg_flag = ref(false);
        
        const handleLogin = () => {
            if (!userInfo.value.isLogin) {
                lg_flag.value = true;
            }
        }
        
        const handleBack = () => {
            lg_flag.value = false;
        }
        
        const handleBlackClick = () => {
            lg_flag.value = false;
        }

        // 从本地存储加载用户信息
        const loadUserInfo = () => {
            const storedUserInfo = localStorage.getItem('userInfo');
            if (storedUserInfo) {
                userInfo.value = JSON.parse(storedUserInfo);
            }
        };

        // 保存用户信息到本地存储
        const saveUserInfo = (info) => {
            userInfo.value = {
                ...info,
                isLogin: true
            };
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
        };

        // 清除用户信息
        const clearUserInfo = () => {
            userInfo.value = {
                nickname: '',
                headimgurl: '',
                isLogin: false,
                email: ''
            };
            localStorage.removeItem('userInfo');
        };

        // 更新界面显示
        const updateUI = () => {
            const picElement = document.querySelector('.pic');
            if (picElement instanceof HTMLElement) {
                if (userInfo.value.isLogin) {
                    picElement.style.backgroundImage = `url(${pic})`;
                } else {
                    picElement.style.backgroundImage = `url(${defaultPic})`;
                }
            }
            // 更新登录按钮文本
            const loginElement = document.querySelector('.login');
            if (loginElement) {
                loginElement.textContent = userInfo.value.isLogin ? (userInfo.value.nickname || '已登录') : '登录';
            }
        };

        // 退出登录
        const handleLogout = () => {
            clearUserInfo();
            // 清除手势验证状态
            localStorage.removeItem('gestureVerified');
            // 清除手势密码
            localStorage.removeItem('gesturePassword');
            // 清除皮肤和图标设置，重置为默认值
            localStorage.removeItem('skin-setting');
            localStorage.removeItem('selected-icon');
            
            // 重置 Vuex 状态
            store.commit('setSkin', {
                img: new URL('@/assets/my/banner.png', import.meta.url).href,
                bgColor: '#fb8fae'
            });
            
            // 手动更新全局 CSS 变量
            document.documentElement.style.setProperty('--skin-bg-color', '#fb8fae');
            document.documentElement.style.setProperty('--skin-bg-image', 'url(' + new URL('@/assets/my/banner.png', import.meta.url).href + ')');
            
            // 触发事件通知 TabBar 更新图标为默认图标
            window.dispatchEvent(new CustomEvent('icon-changed'));
            
            updateUI();
        };

        // 邮箱登录相关
        const email = ref('');
        const verifyCode = ref('');
        const countdown = ref(0);
        const timer = ref(null);
        const isEmailValid = ref(false);

        // 验证邮箱格式
        const validateEmail = () => {
            isEmailValid.value = /^[a-zA-Z0-9._%+-]+@qq\.com$/.test(email.value);
        };

        // 发送验证码
        const sendVerifyCode = async () => {
            if (!isEmailValid.value) {
                messageBox.value.show('请输入正确的QQ邮箱');
                return;
            }
            try {
                console.log('准备发送验证码请求:', {
                    email: email.value,
                    url: '/api/sendCode',
                    network: {
                        online: navigator.onLine,
                        connectionType: navigator.connection ? navigator.connection.type : 'unknown',
                        effectiveType: navigator.connection ? navigator.connection.effectiveType : 'unknown'
                    }
                });
                
                const response = await request.post('/api/sendCode', {
                    email: email.value
                }, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                console.log('验证码发送响应:', response.data);
                
                if (response.data.success) {
                    countdown.value = 60;
                    timer.value = setInterval(() => {
                        countdown.value--;
                        if (countdown.value <= 0) {
                            clearInterval(timer.value);
                        }
                    }, 1000);
                    messageBox.value.show('验证码已发送到您的邮箱，请注意查收');
                } else {
                    messageBox.value.show(response.data.message || '发送验证码失败');
                }
            } catch (error) {
                console.error('发送验证码失败，详细错误:', error);
                
                if (error.response?.status === 429) {
                    messageBox.value.show('发送过于频繁，请稍后再试');
                } else if (error.response?.status === 400) {
                    messageBox.value.show(error.response.data.message || '邮箱格式不正确');
                } else if (error.response?.status === 403) {
                    messageBox.value.show(error.response.data.message || '该邮箱已被限制使用');
                } else if (error.response?.status === 500) {
                    messageBox.value.show('服务器错误，请稍后重试');
                } else if (error.code === 'ECONNABORTED') {
                    messageBox.value.show('请求超时，请检查网络连接');
                } else if (!navigator.onLine) {
                    messageBox.value.show('网络连接已断开，请检查网络设置');
                } else {
                    messageBox.value.show(error.response?.data?.message || '发送验证码失败，请稍后重试');
                }
            }
        };

        // 邮箱登录
        const handleEmailLogin = async () => {
            if (!/^[a-zA-Z0-9._%+-]+@qq\.com$/.test(email.value)) {
                messageBox.value.show('请输入正确的QQ邮箱');
                return;
            }
            if (!/^\d{6}$/.test(verifyCode.value)) {
                messageBox.value.show('请输入6位验证码');
                return;
            }
            try {
                console.log('准备发送登录请求:', {
                    email: email.value,
                    code: verifyCode.value,
                    url: '/api/emailLogin'
                });

                const response = await request.post('/api/emailLogin', {
                    email: email.value,
                    code: verifyCode.value
                }, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                console.log('登录响应:', response.data);

                if (response.data.success) {
                    handleLoginSuccess(response.data.data);
                } else {
                    messageBox.value.show(response.data.message || '登录失败');
                }
            } catch (error) {
                console.error('登录失败:', error);
                if (error.response?.status === 400) {
                    messageBox.value.show(error.response.data.message || '验证码错误或已过期');
                } else if (error.response?.status === 403) {
                    messageBox.value.show(error.response.data.message || '该邮箱已被限制使用');
                } else if (error.response?.status === 429) {
                    messageBox.value.show('登录尝试次数过多，请稍后再试');
                } else if (error.code === 'ECONNABORTED') {
                    messageBox.value.show('请求超时，请检查网络连接');
                } else if (!navigator.onLine) {
                    messageBox.value.show('网络连接已断开，请检查网络设置');
                } else {
                    messageBox.value.show(error.response?.data?.message || '登录失败，请稍后重试');
                }
            }
        };

        // 登录成功后的处理
        const handleLoginSuccess = (data) => {
            // 提取QQ号（从邮箱中提取@前的部分）
            const qqNumber = email.value.split('@')[0];
            
            // 更新用户信息
            userInfo.value = {
                isLogin: true,
                qqNumber: qqNumber,
                avatar: data.avatar || pic
            };
            
            // 存储用户信息到本地
            localStorage.setItem('userInfo', JSON.stringify(userInfo.value));
            
            // 关闭登录框
            lg_flag.value = false;
            
            // 显示登录成功提示
            messageBox.value.show('登录成功');
            
            // 更新UI
            updateUI();
        };

        const messageBox = ref(null);

        const handleFeatureClick = () => {
            if (!userInfo.value.isLogin) {
                lg_flag.value = true;
            }
        };

        onMounted(() => {
            loadUserInfo();
            
            
            // 检查路由参数，如果有showLogin=true则自动打开登录框
            if (route.query.showLogin === 'true') {
                lg_flag.value = true;
            }
            updateUI();
        });
        
        return { 
            myObj, 
            myObj2, 
            lg_flag, 
            handleLogin, 
            handleBack, 
            handleBlackClick, 
            handleLogout, 
            userInfo, 
            email,
            verifyCode, 
            countdown,
            isEmailValid,
            sendVerifyCode,
            handleEmailLogin,
            validateEmail,
            messageBox,
            handleFeatureClick
        }
  }
}
</script>

<style lang='less' scoped>
.box{
    width: 100%;
    color: #fff;
    background-color: #fbfbf1;
    .top_banner{
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 360px;  
        // background-image: v-bind("skinImg");
        background-size: 100% 100%;
        background-repeat: no-repeat;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-evenly;
        .pic{
            margin-top: 80px;
            width: 105px;
            height: 105px;
            border-radius: 100%;
            background-size: 100% 100%;
            background-repeat: no-repeat;
            transition: background-image 0.3s ease;
        }
        .login{
            width: 140px;
            height: 40px;
            border-radius: 15px;
            text-align: center;
            line-height: 40px;
            font-size: 28px;
            border: 1px solid #fff;
            transition: all 0.3s ease;

            &.logged-in {
                border: none;
            }
        }
        .tipText{
            font-size: 24px;
        }
    }
    .content{
        margin-top: 360px;
        width: 100%;
        .itemMax {
            width: 100%;
            margin-bottom: 40px;
            .item{
                width: 100%;
                height: 90px;
                background-color: #fff;
                display: flex;
                align-items: center;
                padding: 0 40px;
                .left{
                    width: 40px;
                    height: 40px;
                }
                .center{
                    width: 550px;
                    margin-left: 20px;
                    font-size: 32px;
                    color: #000;
                    border-bottom: 1px solid #fff;
                }
                .right{
                    width: 30px;
                    height: 30px;
                }
            }
        }
    }
}
.lg_black{
    width: 100%;
    height: 100%;
    background-color: #000;
    opacity: 0.5;
    position: fixed;
    top: 0;
    left: 0;
}
.lg_cont{
    width: 100%;
    height: 850px;
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: #fff;
    z-index: 1000;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    border-radius: 20px 20px 0 0;
    .lg_top{
        width: 100%;
        height: 80px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .lg_back{
            width: 40px;
            height: 80px;
            text-align: center;
            line-height: 80px;
            font-size: 32px;
            color: #000;
            margin-left: 20px;
        }   
        .lg_title{
            margin: 0 auto;
            font-size: 32px;
            color: #000;
        }
    }
    .lg_bannerr{
        width: 130px;
        height: 130px;
        background-image: url('@/assets/my/pic_mr.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
    }
    p{
        text-align: center;
        font-size: 32px;
        color: gray;
    }
    .lg_xy {
        margin-bottom: 40px;
        display: flex;
        align-items: center;
        input {
            width: 30px;
            height: 30px;
        }
        label {
            margin-left: 20px;
            font-size: 24px;
            color: gray;
        }
    }
    
}
.email-login {
    width: 100%;
    height: 400px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .input-group {
        margin-bottom: 30px;
        padding: 0 40px;
        
        input {
            width: 100%;
            height: 80px;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 0 20px;
            font-size: 24px;
            box-sizing: border-box;
        }
    }

    .verify-code {
        display: flex;
        gap: 15px;
        padding: 0 40px;

        input {
            flex: 1;
        }

        .send-code-btn {
            width: 200px;
            height: 80px;
            background: #ccc;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 24px;
            cursor: not-allowed;
            transition: all 0.3s ease;

            &.btn-active {
                background: #007AFF;
                cursor: pointer;

                &:hover {
                    background: #0056b3;
                }
            }

            &:disabled {
                background: #ccc;
                cursor: not-allowed;
            }
        }
    }

    .login-btn {
        width: calc(100% - 80px);
        height: 80px;
        background: #007AFF;
        color: white;
        border: none;
        border-radius: 10px;
        font-size: 24px;
        margin: 30px 40px;
        cursor: pointer;
    }
}
</style>
